#include "gamemanager.h"
#include "shared/common.h"
#include "crypto/zlibhelper.h"

GameManager::GameManager(QObject *parent) :
    QObject(parent)
{

}
Game* GameManager::NewGame(quint64 gid,quint32 pid, quint8 gmode,quint8 maxplayers,quint8 maxlvl,
                    quint8 minlvl,QString name, QString desc)
{
    Game* ngame = new Game(gid,gmode,maxplayers,maxlvl,minlvl,desc,name,pid);
    LGames.insert(gid,ngame);
    _PlayersInGame++;
    return ngame;
}

void GameManager::JoinToGame(quint64 gid, quint32 pid)
{
    if(!LGames.contains(gid) || !LPlayers.contains(pid))
        return;
    LGames[gid]->getPlist()->append(pid);
    LPlayers[pid]->setGame(LGames[gid]);
    _PlayersInGame++;
}

void GameManager::LeaveGame(quint32 pid){

    Game* gg=GetPlayerGame(pid);
    if(gg==NULL)
        return;
    Player* pl=LPlayers[pid];

    gg->getPlist()->removeOne(pid);
    pl->setGame(0);

    if(gg->getPlist()->count()==0)
        LGames.remove(gg->GameId());
    _PlayersInGame--;
}

Game* GameManager::GetGame(quint64 gid){
    if(!LGames.contains(gid))
        return 0;

    return LGames[gid];
}

Game* GameManager::GetPlayerGame(quint32 pid){

    if(LPlayers.contains(pid))
        return LPlayers[pid]->getGame();
    return 0;
}

QByteArray GameManager::GetPktList(){
    QByteArray data;
    if(LGames.count()<1)
        return data;

    QBuffer dev(&data);
    dev.open(QBuffer::ReadWrite);
    QDataStream odata(&dev);
    odata.setByteOrder(QDataStream::LittleEndian);


    QMap<quint64, Game*>::iterator i;
    int fixed_pksize =0x1f;
    for (i = LGames.begin(); i != LGames.end(); ++i)
    {
        Game* gg = (Game*)i.value();
        if(!gg->canJoin())
            continue;

        QByteArray blob((char*)gg->getGInfo(),sizeof(pk_GameInfo));
        ZLibHelper::Compress(&blob);
        quint32 own=gg->getGameOnwer();
        SWAP(own);
        odata << (quint16)  0x0d;
        odata << (quint8)   (fixed_pksize+
                             gg->getGameName().size()+
                             gg->getGameDes().size()+
                             blob.size());
        odata << (quint8)   gg->getGameMode();
        odata << (quint8)   0x0;
        odata << (quint16)  gg->getMinLvl();
        odata << (quint16)  gg->getMaxLvl();
        odata << (quint16)  (C_MAXRANK+gg->getMinLvl());
        odata << (quint8)   gg->getPlist()->count();
        odata << (quint8)   gg->getMaxPlayers();
        odata << (quint32)  own;
        odata << (quint64)  gg->GameId();
        odata << (quint8)   0;
        odata << (quint32)  0x00000200;

        odata << (quint8)   gg->getGameName().size();
        odata.writeRawData(gg->getGameName().toAscii().data(),gg->getGameName().size());
        odata << (quint8)   gg->getGameDes().size();
        odata.writeRawData(gg->getGameDes().toAscii().data(),gg->getGameDes().size());
        odata << (quint16)  blob.size();
        odata.writeRawData(blob.data(),blob.size());
    }

    return data;
}
